import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import { reqInfo, reqLogin, reqLogout } from '@/api/acl/login';
import router from '@/router';
// 引入lodash 深拷贝
import _ from 'lodash'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

// 计算当前路由需要动态添加的路由结果
const findUserAsyncRoutes = (allAsyncRoutes: any, routes: any) => {
  return allAsyncRoutes.filter((item: any) => {
    // 过滤一级路由
    if (routes.indexOf(item.name) != -1) {
      // 过滤二级、三级...路由
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoutes(item.children,routes)
      }
      return true;
    }
  })
}


export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttonsList: []
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        // console.log(result);
        //  仓库存储token
        this.token = result.token
        //持久化存储token
        setToken(result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject('失败')
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        let result = await reqInfo()
        // console.log(result);
        this.name = result.name
        this.avatar = result.avatar
        this.buttonsList = result.buttons
        // 计算异步路由添加的结果
        let userRegisterAsyncRoute = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes), result.routes)
        // console.log(userRegisterAsyncRoute);
        // 追加动态路由：异步路由和任意路由
        this.setRoute([...userRegisterAsyncRoute,anyRoute])
        // 展示左侧目录
        this.menuRoutes = [...staticRoutes,...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 动态添加路由
    setRoute(registerRoute:any){
      // console.log(registerRoute);
      registerRoute.forEach((item:any) => {
        router.addRoute(item)
      });
    },

    // 退出登录
    async reset() {
      try {
        await reqLogout()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 重置路由的方法
    resetRoutes(){
      // 退出登录清除全部路由
      // 获取全部路由信息
      let allRoutes = router.getRoutes()
      // 清除全部路由
      allRoutes.forEach((item:any)=>{
        router.removeRoute(item.name)
      })
      // 动态添加常量路由
      staticRoutes.forEach((item:any)=>{
        router.addRoute(item)
      })
    }
  },
});
